package mspbots.next.ticket.core.grader;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import mspbots.next.ticket.core.client.WiseClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.r2dbc.core.DatabaseClient;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * com.mspbots.core.ticketai.GradeInterceptorAdapter
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/8/20
 */
public abstract class AbstractGradeRuleAdapter implements GradeRuleInterceptor {

    protected ObjectMapper objectMapper;
    protected WiseClient wiseClient;
    protected R2dbcEntityTemplate  r2dbcEntityTemplate;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Autowired
    public void setWiseClient(WiseClient wiseClient) {
        this.wiseClient = wiseClient;
    }

    @Autowired
    public void setR2dbcEntityTemplate(R2dbcEntityTemplate r2dbcEntityTemplate) {
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
    }

    protected Long getLongValueId(JsonNode node) {
        try {
            return ObjectUtils.isEmpty(node) ? null : node.get("id").asLong();
        } catch (Exception e) {
            return null;
        }
    }

    protected String getStringValueName(JsonNode node) {
        try {
            return ObjectUtils.isEmpty(node) ? "" : node.get("name").asText();
        } catch (Exception e) {
            return null;
        }
    }

    protected String getStringValue(JsonNode node) {
        try {
            return ObjectUtils.isEmpty(node) ? "" : node.asText();
        } catch (Exception e) {
            return null;
        }
    }

    protected Integer getIntValueId(JsonNode node) {
        try {
            return ObjectUtils.isEmpty(node) ? null : node.get("id").asInt();
        } catch (Exception e) {
            return null;
        }
    }

    protected Boolean getBooleanValue(JsonNode node) {
        try {
            return ObjectUtils.isEmpty(node) ? null : node.asBoolean();
        } catch (Exception e) {
            return null;
        }
    }
    protected LocalDateTime getDateTimeValue(JsonNode node) {
        try {
            String date = node.asText();
            if (date.length() == 10) {
                date = date + "T00:00:00Z";
            }
            return ObjectUtils.isEmpty(node) ? null : LocalDateTime.parse(date, DateTimeFormatter.ISO_DATE_TIME);
        } catch (Exception e) {
            return null;
        }
    }

    protected String getStringValueIdentifier(JsonNode node) {
        try {
            return ObjectUtils.isEmpty(node) ? "" : node.get("identifier").asText();
        } catch (Exception e) {
            return null;
        }
    }
}
